import Cesium, { AssociativeArray } from '../Ces/Cesium'

interface FrameListener {
  id?: string;
  name?: string;
  isDestroyed(): boolean;
  update(scene: any, time: any): void;
}

class FrameListenerManager {
  private _objects: AssociativeArray;

  constructor() {
    this._objects = new Cesium.AssociativeArray();
  }

  add(framelistener: FrameListener, id: string = ''): any {
    if (!Cesium.defined(id) || id === '') {
      id = Cesium.createGuid();
    }
    this._objects.set(id, framelistener);

    return framelistener
  }

  removeAll(): void {
    for (let i = 0; i < this._objects.length; i++) {
      const obj = this._objects.values[i]
      if (obj.destroy) obj.destroy();
    }
    this._objects.removeAll();
  }

  remove(id: string): boolean {
    if (!Cesium.defined(id)) {
      return false;
    }

    const frm = this._objects.get(id);

    if (!Cesium.defined(frm)) {
      return false;
    }

    if (!this._objects.remove(id)) {
      return false;
    }

    return true;
  }

  update(scene: any, time: any): void {
    const toRemoves: FrameListener[] = [];

    let i = 0;

    for (; i < this._objects.length; i++) {
      const frm = this._objects.values[i];

      if (frm.isDestroyed()) {
        toRemoves.push(frm);
      } else {
        frm.update(scene, time);
      }
    }

    i = 0;
    for (; i < toRemoves.length; i++) {
      const frm = toRemoves[i];

      this.remove(frm.id!);
    }
  }

  destroy(): void {
    Cesium.destroyObject(this);
  }

  isDestroyed(): boolean {
    return false;
  }
}


export default FrameListenerManager;
